package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CostomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 胡慧
 * @title: WmNewsServiceImpl
 * @projectName heima-leadnews
 * @description: TODO
 * @date 2021/2/2316:17
 */
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public void selectNewsById(Integer id) {
        wmNewsMapper.selectById(id);


    }

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //查询当前登录用户的文章
        wrapper.eq(WmNews::getUserId, user.getId());
        //状态精确查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //关键字模糊查询
        if (dto.getKeyword() != null) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //按照时间倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        IPage page = new Page(dto.getPage(), dto.getSize());
        page = page(page, wrapper);
        //封装
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        result.setHost(fileServerUrl);
        return result;
    }



    @Override
    public ResponseResult submitNews(WmNewsDto dto, Short isSubmit) {
        //检查参数
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存到文章
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //如果当前的封面匹配类型是自动 -1
        if (dto.getType() == -1) {
            //从保存文章内容图片与素材的关系中进行匹配规则
            wmNews.setType(null);
        }
        //封面图片的处理
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imageStr = dto.getImages().toString().replace("[", "").replace("]", "")
                    .replace(fileServerUrl, "").replace(" ", "");
            wmNews.setImages(imageStr);
        }
        //2.保存或修改文章以及他的状态
        saveWmNews(wmNews, isSubmit);
        //3.内容图片和素材的关系
        List<String> material = ectractUrlInfo(dto.getContent());

        //当前为提交并且内容中解析出了图片
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode()) && material.size() != 0) {
            ResponseResult responseResult = saveRelativeInfoForContent(material, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        //4.保存文章封面图片与素材的关系
        if (isSubmit.equals(WmNews.Status.SUBMIT.getCode())) {
            ResponseResult responseResult = saveRelativeInfoForCover(dto, material, wmNews);
            if (responseResult != null) {
                return responseResult;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章封面图片与素材的关系
     * 如果当前封面类型为自动，则需要设置图片，
     * 规则为：
     * 如果当前内容中的图片大于2，则是多图 取3章图片作为封面图片
     * 如果当前内容中的图片大于0  小于等于2，则设置为单图 取一张图片
     * 其他情况，为无图
     *
     * @param dto
     * @param material
     * @param wmNews
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> material, WmNews wmNews) {
        //前端传过来的图片集合
        List<String> images = dto.getImages();
        //设置自动匹配封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //如果当前内容中的图片大于2，则是多图 取3章图片作为封面图片
            if (material.size()>2){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=material.stream().limit(3).collect(Collectors.toList());
            } else if (material.size() > 0 && material.size() <= 2) {
                //如果当前内容中的图片大于0  小于等于2，则设置为单图 取一张图片
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = material.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

        //    修改文章信息
            if (images!=null&& images.size()>0){

                wmNews.setImages(StringUtils.join(images.stream().map(x -> x.replace(fileServerUrl, "")).collect(Collectors.toList()), ","));;
            }
            updateById(wmNews);
        }

        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForImage(images, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer id) {
        images = images.stream().map(x->x.replace(fileServerUrl,"")).collect(Collectors.toList());
        return saveRelativeInfo(images, id, WemediaConstants.WM_COVER_REFERENCE);
    }

    /**
     * 保存文章内容图片和素材的关系
     *
     * @param material
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> material, Integer newsId) {
        return saveRelativeInfo(material, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存图片和素材的关系
     *
     * @param material
     * @param newsId
     * @param type
     * @return
     */
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    private ResponseResult saveRelativeInfo(List<String> material, Integer newsId, Short type) {
        //1.获取数据库中的素材信息
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, material)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (dbMaterials == null && dbMaterials.size() == 0) {
            throw new CostomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }
        //2.通过图片的路径获取素材的id

        List<Integer> materialsIds = new ArrayList<>();

        // <sdkjflj.jpg,2>
        Map<String, Integer> urlIdMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String url : material) {
            Integer materialId = urlIdMap.get(url);
            //没找到
            if ("null".equals(materialId)) {
                throw new CostomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            //找到了
            materialsIds.add(materialId);

        }

        //3.批量保存
        wmNewsMaterialMapper.saveRelations(materialsIds, newsId, type);
        return null;
    }

    /**
     * 抽取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                materials.add(imgUrl);
            }
        }
        return materials;
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews
     * @param isSubmit
     */

    @Autowired
    private KafkaTemplate kafkaTemplate;
    public void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);//上架

        boolean flag = false;
        if(wmNews.getId() == null){
            //保存
            flag =save(wmNews);
        }else {
            //修改
            //先删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            flag = updateById(wmNews);
        }
        //发送消息审核
        if(flag){
            kafkaTemplate.send(NewsAutoScanConstants.auot_topic,JSON.toJSONString(wmNews.getId()));
        }

    }

    /**
     * 自媒体文章的上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //文章是否存在
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            if (wmNews.getArticleId()!=null){
                //封装消息
                HashMap<String, Object> map = new HashMap<>();
                map.put("enable",dto.getEnable() );
                map.put("articleId",wmNews.getArticleId());
                kafkaTemplate.send(WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));

            }
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage,dto.getSize(),count);
        responseResult.setData(wmNewsVoList);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

@Autowired
private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult=new ResponseResult();
        responseResult.setData(wmNewsVo);
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }

    /**
     * 自媒体文章审核人工审核
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //结果返回
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(fileServerUrl);
        return result;
    }


    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //获取数据
        WmNews news = getById(id);
        if(news == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断当前文章的状态
        if(news.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && news.getEnable().equals(WemediaConstants.WM_NEWS_ENABLE_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
         wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
        //5.删除文章
        removeById(news.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
